// -----------------------------------------------------------------------------
// This source file is part of Matrix Platform
// 	(Universal .NET Software Development Platform)
// For the latest info, see http://www.matrixplatform.com
// 
// Copyright (c) 2009-2010, Ingenious Ltd
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// -----------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Runtime.Serialization;
using Matrix.Common.Core;
using Matrix.Common.Core.Collections;
using Matrix.Common.Diagnostics.TracerCore.Items;

namespace Matrix.Common.Diagnostics.TracerCore.Filters
{
    /// <summary>
    /// Tracer item filter, allows filtering based on originating assembly, class and (method)}.
    /// </summary>
    [Serializable]
    public class MethodTracerFilter : TracerFilter
    {
        public class AssemblyTracingInformation
        {
            public bool Enabled = true;
            public Dictionary<string, bool> TypesNames = new Dictionary<string, bool>();
        }

        HotSwapDictionary<string, AssemblyTracingInformation> _assembliesHotSwap = new HotSwapDictionary<string, AssemblyTracingInformation>();
        
        /// <summary>
        /// Thread safe access.
        /// </summary>
        public ICollection<string> Assemblies
        {
            get 
            {
                return _assembliesHotSwap.Keys;
            }
        }

        /// <summary>
        /// Constructor.
        /// </summary>
        public MethodTracerFilter()
        {
            foreach (Assembly assembly in ReflectionHelper.GetAssemblies(true, true))
            {
                object[] copyright = assembly.GetCustomAttributes(typeof(AssemblyCopyrightAttribute), true);
                if (copyright != null && copyright.Length > 0)
                {// Skip system assemblies.
                    AssemblyCopyrightAttribute attribute = (AssemblyCopyrightAttribute)copyright[0];
                    if (attribute.Copyright.Contains("Microsoft"))
                    {
                        continue;
                    }
                }

                _assembliesHotSwap.Add(assembly.GetName().Name, new AssemblyTracingInformation());
            }
        }

        /// <summary>
        /// Deserialization constructor.
        /// </summary>
        /// <param name="info"></param>
        /// <param name="context"></param>
        public MethodTracerFilter(SerializationInfo info, StreamingContext context)
            : base(info, context)
        { 
        }


        /// <summary>
        /// 
        /// </summary>
        public AssemblyTracingInformation GetAssemblyInfo(string assemblyName)
        {
            AssemblyTracingInformation result = null;
            _assembliesHotSwap.TryGetValue(assemblyName, out result);

            return result;
        }

        /// <summary>
        /// 
        /// </summary>
        public override bool FilterItem(TracerItem item)
        {
            if (item is MethodTracerItem == false)
            {
                return true;
            }

            bool updated = false;
            bool result = false;
            
            MethodTracerItem actualItem = (MethodTracerItem)item;
            if (actualItem.DeclaringAssembly != null
                && string.IsNullOrEmpty(actualItem.DeclaringTypeName) == false)
            {
                AssemblyTracingInformation info;
                if (_assembliesHotSwap.TryGetValue(actualItem.DeclaringAssemblyName, out info) == false)
                {// Add assembly.
                    AssemblyTracingInformation newInfo = new AssemblyTracingInformation();
                    info = _assembliesHotSwap.GetOrAdd(actualItem.DeclaringAssemblyName, newInfo);
                    updated = newInfo == info;
                }

                if (info.Enabled == false)
                {// Entire assembly stopped.
                    return false;
                }

                if (info.TypesNames.ContainsKey(actualItem.DeclaringTypeName) == false)
                {// Add type.
                    info.TypesNames.Add(actualItem.DeclaringTypeName, true);
                    updated = true;
                    result = true;
                }
                else
                {
                    return info.TypesNames[actualItem.DeclaringTypeName];
                }
            }
            else
            {// Item has no method info assigned, pass it trough.
                result = true;
            }

            if (updated)
            {
                RaiseFilterUpdatedEvent(true);
            }

            return result;
        }
    }
}
